package com.fingard.dsp.bank.directbank.cmb04;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.ReqQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.RetAtsQryRefund;
import com.fingard.dsp.bank.reqrespobj.qryrefund.detail.RetAtsRefundDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.GZipHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.Calendar;

public class CMB04QryRefund extends CMB04Base implements IQryRefund {
	@Override
	public RetAtsQryRefund d_qry_refund(ReqQryRefund p_req) throws Exception {
		RetAtsQryRefund retAts = new RetAtsQryRefund(p_req.reqHeader);
        retAts.writeStart();

        String tmpRespCode = "";
        String tmpRespInfo = "";
        
        int tmpSuccCount = 0;
        BigDecimal tmpTotalAmt = new BigDecimal("0");

        SftpPortClient sftpPortClient = null; 
        
        try {
        	Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req.getQryStartDate());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req.getQryEndDate());
            tmpCalendarTo.add(Calendar.DAY_OF_MONTH, 1);
            
            while (tmpCalendarFrom.compareTo(tmpCalendarTo) == -1) {
            	ActSetItem actItem = getBankConfig().getActSetItem(p_req.payAct, "");
    			if (actItem == null) {
    				retAts.writeRespCode("-1");
    				retAts.writeRespInfo("未找到账号:[" + p_req.payAct + "]商户配置信息!");
    				retAts.writeEnd();
    		        return retAts;
    			}
    			
    			CMB04Header bankHeader = new CMB04Header();
    			bankHeader.transCode = CMB04TransCode.deal_qryRefund;
    			bankHeader.reqSeqID = getQryTransID();

    			XmlTextWriter xmlWriter = new XmlTextWriter();
    			xmlWriter.autoFormat = false;
    			writeCommonHeader(xmlWriter);

    			xmlWriter.writeStartElement("Request");
    			xmlWriter.writeElementString("merTrnSerial", getQryTransID());
    			xmlWriter.writeElementString("cancelDt", Format.Date8Format.format(tmpCalendarFrom.getTime()));
    			xmlWriter.writeEndDocument();
    			
    			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), bankHeader, actItem);

    			if (tmpStrRet[0].length() == 0) {
    				StringBuilder tmpSbMsg = new StringBuilder();
    				String tempstr = tmpStrRet[1].substring(tmpStrRet[1].indexOf("<?xml"),tmpStrRet[1].indexOf("</Response>")+11);
    				XmlTextReader tmpBkReader = loadBankRespXmlReader(tempstr, tmpSbMsg);
    				if (tmpBkReader != null) {
    					String tmpRetCode = tmpBkReader.getFirstText("/Response/respCode");
    					if ("CMBMB99".equals(tmpRetCode)) {
    						String tmpDownFileName = tmpBkReader.getFirstText("/Response/fileName");
    						if(tmpDownFileName ==null || "".equals(tmpDownFileName)){
								WriteBankLogLn(Format.Date8Format.format(tmpCalendarFrom.getTime())+"退票文件不存在");
								continue;
							}

    						WriteBankLogLn("待下载结果文件名:" + tmpDownFileName);
    						
    						String tmpLocalMarkPath = createTempFileDirectory() + File.separator + tmpDownFileName;
    						WriteBankLogLn2("下载结果文件保存本地路径: " + tmpLocalMarkPath);
    						
    						FtpSet ftpSet = bankFront.getFtpSet("qryRefund");
    						String sftpFilePath = StringHelper.trimEnd(ftpSet.getDownDir("qryRefund"), "/") + "/" + tmpDownFileName;
    						WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
    						sftpPortClient = new SftpPortClient(ftpSet);
    						FtpReceiver ftpReceiver = sftpPortClient.downloadFile("", sftpFilePath, tmpLocalMarkPath);
    						if (ftpReceiver.isCompleted) {
    							GZipHelper.doUncompressFile(tmpLocalMarkPath);
    							String tmpUnCompressFilePath = GZipHelper.getFileName(tmpLocalMarkPath);
    							WriteBankLogLn("解压后文件本机路径:" + tmpUnCompressFilePath);
    							
    							String tmpRetStr = FileHelper.readFileText(tmpUnCompressFilePath, getCharset());
    							WriteBankLogLn2("解压后结果数据:\r\n" + tmpRetStr);
    							
    							StringReader strReader = new StringReader(tmpRetStr);
    							BufferedReader tmpReader = new BufferedReader(strReader);
								tmpReader.readLine();
								tmpReader.readLine();
    							while(true) {
    								String eachline = tmpReader.readLine();
    								if(eachline == null){
    									break;
    								}
    								
    								String[] bodyValues = eachline.split(",");
    								
    								RetAtsRefundDetail tmpRetDetail = new RetAtsRefundDetail();

                                    tmpRetDetail.askNum = bodyValues[0];
                                    tmpRetDetail.payAct = bodyValues[9];
                                    tmpRetDetail.recAct = bodyValues[10];
                                    tmpRetDetail.recActName = bodyValues[11];
                                    tmpRetDetail.amount = bodyValues[8];
                                    tmpRetDetail.refundTicketDate = Format.Date10Format.format(tmpCalendarFrom.getTime());
                                    tmpRetDetail.submitTime = Format.DateTimeFormat.format(tmpCalendarFrom.getTime());
                                    tmpRetDetail.refundTicketReason = bodyValues[3];

                                    tmpSuccCount++;
                                    tmpTotalAmt = tmpTotalAmt.add(new BigDecimal(tmpRetDetail.amount));

                                    retAts.writeRetDetailOnly(tmpRetDetail);
    							}
    						} else {
    							tmpRespCode = "-1";
            					tmpRespInfo = ftpReceiver.connMsg;
    						}
    					} else {
    						tmpRespCode = "-1";
        					tmpRespInfo = tmpBkReader.getFirstText("/Response/respMsg");
    					}
    				} else {
    					tmpRespCode = "-1";
    					tmpRespInfo = tmpSbMsg.toString();
    				}
    			} else {
    				tmpRespCode = "-1";
    				tmpRespInfo = tmpStrRet[1];
    			}    			
                
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
            }
            
            retAts.totleAmount = Format.DecimalAmtFormat.format(tmpTotalAmt);
            retAts.totleNum = String.valueOf(tmpSuccCount);
            retAts.writeTotalInfo();
        } catch (Exception ex) {
        	ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
        	if (sftpPortClient != null) {
        		sftpPortClient.disconnect();
        	}
        }

        if ("-1".equals(tmpRespCode)) {
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("当前时间范围内无退票数据");
        }

        retAts.writeEnd();
        return retAts;
	}
}
